package com.dbkj.axb;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dbkj.axb_conf.AxbConfService;
import com.dbkj.axb_group.AxbGroupService;
import com.dbkj.common.model.Axb;
import com.dbkj.common.pojo.Xpojo;
import com.dbkj.common.utils.RedisUtils;
import com.dbkj.common.utils.UploadDataListener;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.Restful;
import com.jfinal.json.Json;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Max
 * X号码
 * @Date: 2019/10/28 17:10
 */



public class AxbController extends Controller {

    @Inject
    AxbService service;

    @Inject
    AxbGroupService axbGroupService;

    @Inject
    AxbConfService axbConfService;

    @Before(Restful.class)
    public void index(){
        Integer pageNumber = getParaToInt("pageNumber");
        Integer pageSize = getParaToInt("pageSize");
        String telX = getPara("telX");              //x号
        String companyName = getPara("companyName");//x号使用者
        String expiration = getPara("expiration"); // 解绑周期
        String areaCode = getPara("areaCode");     //归属区号
        String concurrent = getPara("concurrent");  //时刻并发
        String aGroup = getPara("aGroup");          //x群
        String groupId = getPara("groupId");    //归属群
        String remark = getPara("remark");          //备注

        Page<Axb> page = service.paginate(pageNumber,pageSize,telX,companyName,expiration,areaCode,concurrent,aGroup,groupId,remark);

        List<Axb> list = page.getList();
        for(Axb x:list){
            String telx = x.getTelX();
            Long len = 0L;
            if(PropKit.getBoolean("is_cluster")){
                len = RedisUtils.cluster.llen("telx_"+telx+"_concurrent_list");
            }else {
                len = RedisUtils.jedis.llen("telx_"+telx+"_concurrent_list");
            }
            x.setCurrentX(len);
        }
        renderJson(Ret.ok().set("total",page.getTotalRow()).set("rows", JSON.toJSON(page.getList())));
    }

    @Before(Restful.class)
    public void save(){
        Axb x = Json.getJson().parse(getRawData(),Axb.class);
        if(StrKit.notBlank(x.getConcurrent())){
            if(PropKit.getBoolean("is_cluster")){
                RedisUtils.cluster.del("telx_"+x.getTelX()+"_concurrent_list");
                for(int k=0;k<Integer.parseInt(x.getConcurrent());k++){
                    RedisUtils.cluster.lpush("telx_"+x.getTelX()+"_concurrent_list","1");
                }
            } else {
                RedisUtils.jedis.del("telx_"+x.getTelX()+"_concurrent_list");
                for(int k=0;k<Integer.parseInt(x.getConcurrent());k++){
                    RedisUtils.jedis.lpush("telx_"+x.getTelX()+"_concurrent_list","1");
                }
            }

        }
        x.save();
        renderJson(Ret.ok());
    }

    @Before(Restful.class)
    public void delete(){
        service.delete(getParaToInt());
        renderJson(Ret.ok());
    }

    public void deleteBatch(){
        JSONObject object = JSONObject.parseObject(getRawData());
        JSONArray array = object.getJSONArray("ids");
        service.deleteBatch(array);
        renderJson(Ret.ok());
    }

    @Before(Restful.class)
    public void update(){
        Json.getJson().parse(getRawData(),Axb.class).update();
        renderJson(Ret.ok());
    }

    public void updateBatch(){
        JSONObject json = JSONObject.parseObject(getRawData());
        JSONObject params = json.getJSONObject("params");
        String telX = params.getString("telX");
        String companyName = params.getString("companyName");
        String expiration = params.getString("expiration");
        String areaCode = params.getString("areaCode");
        String concurrent = params.getString("concurrent");
        String aGroup = params.getString("aGroup");
        String groupId = params.getString("groupId");
        String remark = params.getString("remark");

        String key = json.getString("key");
        String value = json.getString("value");
        service.updateBatch(telX,companyName,expiration,areaCode,concurrent,aGroup,groupId,remark,key,value);
        renderJson(Ret.ok());
    }

    public void use(){
        JSONObject json = JSONObject.parseObject(getRawData());
        Integer id = json.getInteger("ids");
        Boolean isUse = json.getBoolean("isUse");
        if(isUse){
            Db.update("update axb set is_use = 1 where id=?",id);
        } else {
            Db.update("update axb set is_use = 0 where id=?",id);
        }
        renderJson(Ret.ok());
    }

    public void current(){
//        JSONObject json = JSONObject.parseObject(getRawData());
        JSONArray array = JSONArray.parseArray(getRawData());
        for(int i=0;i<array.size();i++){
            JSONObject object = array.getJSONObject(i);
            String telX = object.getString("telX");
            Integer currentXOld = object.getInteger("currentXOld");
            Integer currentX = object.getInteger("currentX");

            if(PropKit.getBoolean("is_cluster")){
                if(currentX < currentXOld){
                    for(int j=0;j<currentXOld-currentX;j++){
                        RedisUtils.cluster.rpop("telx_"+telX+"_concurrent_list");
                    }
                } else if(currentX > currentXOld){
                    for(int j=0;j<currentX - currentXOld;j++){
                        RedisUtils.cluster.lpush("telx_"+telX+"_concurrent_list","1");
                    }
                }
            } else {
                if(currentX < currentXOld){
                    for(int j=0;j<currentXOld-currentX;j++){
                        RedisUtils.jedis.rpop("telx_"+telX+"_concurrent_list");
                    }
                } else if(currentX > currentXOld){
                    for(int j=0;j<currentX - currentXOld;j++){
                        RedisUtils.jedis.lpush("telx_"+telX+"_concurrent_list","1");
                    }
                }
            }
        }
        renderJson(Ret.ok());
    }


    public void importExcel() throws IOException {
        UploadFile file = getFile();
        if(null == file){
            renderError(400);
        }

        File excelFile = file.getFile();
        InputStream inputStream = new FileInputStream(excelFile);
        List<Object> data = EasyExcelFactory.read(inputStream,new Sheet(1,1));
        inputStream.close();

        boolean flag = false;


        ok:
        for(int i=0;i<data.size();i++){
            String str = data.get(i).toString();
            str = str.replaceAll(" ","");
            str = str.replaceAll("null","");
            str = str.replaceAll("\n","").replaceAll("\t","").replaceAll("\r","");
            String[] arr = str.substring(1,str.length()-1).split(",");

            Axb x = new Axb();

            for(int j=0;j<arr.length;j++){
                if(j==0){
                    x.setTelX(arr[0]); //x号码
                } else if(j==1){
                    x.setAreaCode(arr[1]);//归属区号
                } else if(j==2){
                    x.setExpiration(Integer.valueOf(arr[2]));//解绑周期
                } else if(j==3) {
                    x.setConcurrent(arr[3]);//时刻并发数
                } else if(j==4){
                    x.setCompanyName(arr[4]);//x号使用者
                }else if(j==5){
                    x.setAGroup(arr[5]);//x群
                } else if(j==6){
                    Integer id = axbGroupService.getIdByName(arr[6]);
                    if(id == null){
                        flag = true;
                        break ok;
                    }
                    x.setGroupId(id);//归属群
                }  else if(j==7){
                    Integer id = axbConfService.getIdByName(arr[7]);
                    if(id == null){
                        flag = true;
                        break ok;
                    }
                    x.setConfId(id);//关联配置
                } else if(j==8){
                    x.setRemark(arr[8]);
                } else if(j==9){
                    if(arr[9].equals("是")){
                        x.setIsUse(true);
                    }else{
                        x.setIsUse(false);
                    }
                }
            }
            if(StrKit.notBlank(x.getConcurrent())){
                if(PropKit.getBoolean("is_cluster")){
                    RedisUtils.cluster.del("telx_"+x.getTelX()+"_concurrent_list");
                    for(int k=0;k<Integer.parseInt(x.getConcurrent());k++){
                        RedisUtils.cluster.lpush("telx_"+x.getTelX()+"_concurrent_list","1");
                    }
                }else{
                    RedisUtils.jedis.del("telx_"+x.getTelX()+"_concurrent_list");
                    for(int k=0;k<Integer.parseInt(x.getConcurrent());k++){
                        RedisUtils.jedis.lpush("telx_"+x.getTelX()+"_concurrent_list","1");
                    }
                }

            }
            x.setIsUse(true);
            x.save();
        }
        file.getFile().delete();
        if(flag){
            renderError(422, new JsonRender(Ret.by("code",422).set("msg","填写的数据有问题,请查看群/组/相关配置的数据")));
            return;
        }
        renderJson(Ret.ok());
    }

    //利用新版easyExcel进行导入测试
    public void newimportExcel(){
        UploadFile file = getFile();
        EasyExcel.read(file.getFile(),new UploadDataListener()).sheet().doRead();
        renderNull();
    }


    public void getExcelModel(){
        File filetemp = new File(PropKit.get("file_addr")+"axba.xlsx");
        File fparent = filetemp.getParentFile();
        if(!fparent.exists()){
            fparent.mkdirs();
        }
        String fileName = PropKit.get("file_addr")+"axb.xlsx";
        EasyExcel.write(fileName, Xpojo.class).sheet("x号码").doWrite(new ArrayList());
        renderFile(new File(fileName));
    }


    public void bind() throws IOException {
        JSONObject json = JSONObject.parseObject(getRawData());
        Integer confId = json.getInteger("confId");
        String telB = json.getString("telB");
        String aGroup = json.getString("aGroup");

        HttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(PropKit.get("telx_bind"));

        post.setHeader("Content-Type","application/x-www-form-urlencoded");
        post.setHeader("Accept","application/json");

        ArrayList<NameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("AGroup",aGroup));
        list.add(new BasicNameValuePair("telB",telB));

        post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
        HttpResponse response = httpClient.execute(post);

        int status = response.getStatusLine().getStatusCode();
        if(status ==200){
            HttpEntity responseEntity = response.getEntity();
            JSONObject object = JSONObject.parseObject(EntityUtils.toString(responseEntity));
            if("success".equals(object.getString("reason"))){
                renderJson(Ret.ok().set("msg",object));
            }else{
                renderJson(Ret.fail().set("msg",object));
            }

            /*String type = axbConfService.getTypeById(confId);
            if(type.startsWith("gx")){
                //广西
                String code = object.getString("code");
                String message = object.getString("message");
                if("0".equals(code)){
                    renderJson(Ret.ok().set("code",code).set("msg",message));
                }else {
                    renderJson(Ret.fail().set("code",code).set("msg",message));
                }
            } else if(type.startsWith("dx")){
                //东信
                Boolean success = object.getBoolean("success");
                String code = object.getString("code");
                String message = object.getString("message");
                if(success){
                    renderJson(Ret.ok().set("code",code).set("msg",message));
                } else {
                    renderJson(Ret.fail().set("code",code).set("msg",message));
                }
            } else if(type.startsWith("yd")) {
                //移动
                Integer resultCode = object.getInteger("resultCode");
                String resultMsg = object.getString("resultMsg");
                if(resultCode == 0){
                    renderJson(Ret.ok().set("code",resultCode.toString()).set("msg",resultMsg));
                }else{
                    renderJson(Ret.fail().set("code",resultCode.toString()).set("msg",resultMsg));
                }
            } else if(type.startsWith("hw")) {
                //华为
                String resultcode = json.getString("resultcode");
                String resultdesc = json.getString("resultdesc");
                if("0".equals(resultcode)){
                    renderJson(Ret.ok().set("code",resultcode).set("msg",resultdesc));
                } else {
                    renderJson(Ret.fail().set("code",resultcode).set("msg",resultdesc));
                }
            }*/
        }
    }
}
